import os

from DrissionPage import ChromiumPage, ChromiumOptions
import tkinter as tk
from tkinter import filedialog


GREEN = '\033[92m'
GREEN_END = '\033[0m'
RED = '\033[31m'
RED_END = '\033[0m'
PURPLE = '\033[35m'  # 实际上这是品红色（Magenta），在某些终端上可能看起来接近紫色
PURPLE_END = '\033[0m'


def save_to_txt(filename, list_to_save):
    if list_to_save:  # 检查列表是否为空
        with open(filename, 'a', encoding='utf-8') as file:  # 使用追加模式打开文件
            for item in list_to_save:
                file.write(item + '\n')  # 将列表中的每个元素写入文件，并在末尾添加换行符
                # 如果你想要以特定格式保存（例如JSON或CSV），你可以在这里修改写入逻辑
    else:
        print(f"列表为空，没有写入到 {filename}")


def open_file_dialog():
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    root.attributes('-topmost', 1)
    file_path = filedialog.askopenfilename(title="选择文本文件", filetypes=[("Text Files", "*.txt")])

    if file_path:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read().splitlines()

        print('文本文件内容:')
        print(content)
        return content
    else:
        print('未选择文件')
        return []


def chrom_page():
    try:
        path = fr'{chrome_path}'  # 请改为你电脑内Chrome可执行文件路径
        co = ChromiumOptions().auto_port()
        co.set_browser_path(path)
        page = ChromiumPage(co)
        # 设置窗口最大化
        page.set.window.max()
        # 访问网页
        page.get('https://www.xiaohongshu.com/')
        return page
        # co = ChromiumOptions().headless()
        # co.set_user_agent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0')
        # page = ChromiumPage(co)
        # # 设置窗口最大化
        # # page.set.window.max()
        # # 访问网页
        # page.get('https://www.xiaohongshu.com/')
        # return page
    except Exception as e:
        print(e)
        return chrom_page()


def get_xhs_list(page_driver, keyword):
    """
    获取小红书下拉词
    :param page_driver: 实例化ChromiumPage对象
    :param keyword: 查询的关键词
    :return:返回一个下拉词LIST
    """
    try:
        xhs_res_list = []
        global repeat_list
        page_driver.listen.start('/api/sns/web/v1/search/recommend?keyword')  # 开始监听，指定获取包含该文本的数据包
        page_driver.ele('x://*[@id="search-input"]').input(f'{keyword}', clear=True)
        # encoded_str = quote(keyword)  # 关键词进行URL编码来匹配数据包
        temp_list = []  # 打印输出当前关键词结果
        while True:
            res = page_driver.listen.wait()  # 等待并获取一个数据包
            print(f'监听数据包：{res.url}')
            if res.response.body['code'] == 1000:
                # print(f'成功获取响应结果：{res.response.body}')  # res.response.body监听到的数据包的响应结果
                print(f'{GREEN}成功获取响应结果：{res.response.body}{GREEN_END}')
                res_list = res.response.body['data']['sug_items']
                for res in res_list:
                    temp_list.append(res['text'])
                    xhs_res_list.append(res['text'])
                    repeat_list.append(res['text'])
                print(f'{GREEN}{str(temp_list)}{GREEN_END}')
                print(f'{GREEN}---------------------{GREEN_END}')
                return xhs_res_list
            else:
                print(f'{RED}获取异常：{res.response.body}{RED_END}')
                print(f'{RED}---------------------{RED_END}')
                return []  # 如果响应结果为空返回一个空列表
    except Exception as e:
        print(e)


if __name__ == '__main__':
    if not os.path.exists('./小红书_res'):
        os.makedirs('./小红书_res')
    try:
        global chrome_path
        # 打开文件并读取内容
        with open('chrome_path.txt', 'r', encoding='utf-8') as file:
            lines = file.readlines()
        # 遍历每一行，找到包含'chrome.exe'的行
        for line in lines:
            if 'chrome.exe' in line:
                chrome_path = line.strip()
                print(f'可执行文件路径读取成功：{chrome_path}')
                break
    except:
        print('未找到chrome_path可执行文件路径')
    repeat_list = []  # 去除重复用的列表
    query_word_list = open_file_dialog()
    if len(query_word_list) != 0:
        xhs_page = chrom_page()
        if xhs_page.ele('x://*[@id="app"]/div[1]/div/i'):  # 如果出现登录关闭登录按钮
            xhs_page.ele('x://*[@id="app"]/div[1]/div/i').click()
            for index, query_word in enumerate(query_word_list):
                print(f'{PURPLE}当前查询总数{len(query_word_list)}，当前查询到第{index + 1}个，当前查询关键词：{query_word}{PURPLE_END}')
                res_xhs = get_xhs_list(xhs_page, query_word)
                # 检查列表是否为空并决定是否写入文件
                if res_xhs:
                    save_to_txt('./小红书_res/xhs_res_1.txt', res_xhs)
            # xhs_page.close()
        # 转换为集合以删除重复项
        unique_set = set(repeat_list)
        # 再将集合转回列表
        repeat_list = list(unique_set)
        save_to_txt('./小红书_res/xhs_res_去重_1.txt', repeat_list)
        # 进行第二遍查询
        if os.path.isfile('./小红书_res/xhs_res_1.txt'):  # 如果这个文件存在进行第二次查询
            print('进行第二次查询中：----------------------------------------------------------------------------------------')
            repeat_list = []  # 情况去重列表
            # xhs_res_list = []  # 情况列表
            with open('./小红书_res/xhs_res_1.txt', 'r', encoding='utf-8') as file:
                two_query_word_list = file.read().splitlines()  # 读取文件转成列表二次查询
            for index, query_word in enumerate(two_query_word_list):
                print(f'{PURPLE}当前查询总数{len(two_query_word_list)}，当前查询到第{index + 1}个，当前查询关键词：{query_word}{PURPLE_END}')
                res_xhs = get_xhs_list(xhs_page, query_word)
                # 检查列表是否为空并决定是否写入文件
                if res_xhs:
                    save_to_txt('./小红书_res/xhs_res_2.txt', res_xhs)
            xhs_page.close()
            # 转换为集合以删除重复项
            unique_set = set(repeat_list)
            # 再将集合转回列表
            repeat_list = list(unique_set)
            # 进行第二遍查询
            save_to_txt('./小红书_res/xhs_res_去重_2.txt', repeat_list)
